#include "StdAfx.h"
#include "ADSR.h"


CADSR::CADSR(void)
{
	m_attack = 0.05;
    m_release = 0.3;
    m_duration = 0.5;
    m_source = NULL;
	m_decay = 0.05;
	m_attackFactor = 1.15;
}


CADSR::~CADSR(void)
{
}

void CADSR::Start()
{
    m_time = 0.;
}

bool CADSR::Generate()
{
    double gain = 0.;

    if(m_time < m_attack)
    {
        gain = (m_time / m_attack) * m_attackFactor;
    }
	else if(m_time > m_attack && m_time < (m_attack + m_decay) && m_time < m_duration*(1./(m_bpm/60.)))
	{
		double decayperiod = (m_time - m_attack) / m_decay;
		gain = m_attackFactor - ((m_attackFactor - 1) * decayperiod);
	}
    else if(m_time >= m_duration*(1./(m_bpm/60.)) - m_release && m_time <= m_duration*(1./(m_bpm/60.)))
    {
        gain = ((m_duration*(1./(m_bpm/60.)) - m_time) / m_release);
    }
    else
    {
        gain = 1.;
    }

    if(m_source != NULL)
    {
        m_frame[0] = m_source->Frame(0) * gain;
        m_frame[1] = m_source->Frame(1) * gain;
    }
		
    m_time += GetSamplePeriod();
    return m_time < m_duration*(1./(m_bpm/60.));
}